package mil.af.amc.adpetracker.web.actions.dra;

import mil.af.amc.adpetracker.web.actions.AbstractAction;
import mil.af.amc.adpetracker.service.DraService;
import mil.af.amc.adpetracker.service.exceptions.DraExistsException;
import mil.af.amc.adpetracker.model.DRA;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Please Fill in this Javadoc
 *
 * @author TSgt Jason Ferguson
 */

public class CreateDraAction extends AbstractAction {

    private static final Log log = LogFactory.getLog(CreateDraAction.class);

    private DraService draService;

    public void setDraService(DraService draService) {
        this.draService = draService;
    }

    @Override
    public ActionForward execute(ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {

        DynaActionForm draForm = (DynaActionForm) actionForm;
        ActionMessages errors = draForm.validate(actionMapping, httpServletRequest);

        if (!errors.isEmpty()) {
            saveErrors(httpServletRequest, errors);
            actionMapping.getInputForward();
        }

        DRA dra;
        try {
            dra = draService.addDra(draForm.getMap());
        } catch (DraExistsException e) {
            errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.dra.alreadyexists", draForm.getMap().get("draName")));
            return actionMapping.getInputForward();
        }
        if (dra == null) {
            Integer draId = (Integer) draForm.getMap().get("draId");
            errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.dra.notfound", draId));
            return actionMapping.getInputForward();
        }

        return actionMapping.findForward("successAddDra");
    }
}
